/*
 * @lc app=leetcode.cn id=236 lang=cpp
 *
 * [236] 二叉树的最近公共祖先
 */

// @lc code=start
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution
{
public:
    TreeNode *lowestCommonAncestor(TreeNode *root, TreeNode *p, TreeNode *q)
    {
        //寻找二叉树的最近公共祖先
        //找祖先一定是从下往上 所以是后序遍历
        //终止条件
        if (root == q || root == p || root == NULL)
        {
            return root;
        }
        //后序遍历
        TreeNode *left = lowestCommonAncestor(root->left, p, q);
        TreeNode *right = lowestCommonAncestor(root->right, p, q);
        //中 处理
        if (left != NULL && right != NULL)
        {
            //左右都不为空 说明找到了p，q返回他两的父节点root
            return root;
        }
        else if (left == NULL && right != NULL)
        {
            //左节点为空 用右节点传递下面找到的p或q
            return right;
        }
        else if (left != NULL && right == NULL)
        {
            //同上
            return left;
        }
        else
        {
            //均为空 直接返回NULL
            return NULL;
        }
    }
};
// @lc code=end

